package net.esj.basic.plugins.struts2.resultsupport;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.esj.basic.utils.Validators;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.config.DefaultSettings;
import org.apache.struts2.views.freemarker.FreemarkerResult;
import org.apache.struts2.views.freemarker.ScopesHashModel;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class FreemarkerStaticResult extends FreemarkerResult {

	private static final long serialVersionUID = -3778230771704661631L; 
	
	private static final String STRUTS_FREEMARKER_STATIC_PATH= "struts.freemarker.static.path"; //绝对路径
	private static final String STRUTS_FREEMARKER_STATIC_POSTFIX= "struts.freemarker.static.postfix"; 
	
	public static final String STRUTS_FREEMARKER_STATIC_FILE_NAME = "struts.freemarker.static.file.name";
	
	private static final String STRUTS_EXTEND_DEBUG = "struts.extend.debug";
	
	private String postfix = "html";
	
	private String staticPath;
	
	@Override
	protected boolean preTemplateProcess(Template template, TemplateModel model)
			throws IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		
		String fileName = request.getParameter(STRUTS_FREEMARKER_STATIC_FILE_NAME);
		
		Writer out = new BufferedWriter(new OutputStreamWriter(  
						new FileOutputStream(getStaticPath() + fileName)));   
 
		try {
			template.process(model, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		//invocation.getInvocationContext().
		//request.getRequestURI();
		
		return super.preTemplateProcess(template, model);
	}

	public String getStaticPath() {
		if(staticPath==null){
			staticPath = DefaultSettings.get(STRUTS_FREEMARKER_STATIC_PATH);
		}
		return staticPath;
	}
	
	
	public String getPostfix() {
		String str = DefaultSettings.get(STRUTS_FREEMARKER_STATIC_POSTFIX);
		if(!Validators.isEmpty(str)){
			postfix = str;
		}
		return postfix;
	}

	public boolean isDebug(){
		String str = DefaultSettings.get(STRUTS_EXTEND_DEBUG);
		if(Validators.isEmpty(str)){
			return false;
		}
		return Boolean.valueOf(str);
	}
	
}
